﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text.RegularExpressions;
using System.Data;
using EnterpriseFund.Common;
using System.IO;
using System.Text;

namespace EnterpriseFund.Controllers
{
    public class htmlToStrController : Controller
    {
        //
        // GET: /htmlToStr/

        public ActionResult Index(string cls)
        {
             
            if (cls != "")
            {
                BLL.Common CommonBLL = new BLL.Common();
                DataSet ds = CommonBLL.GetCompareDataBySQL("t_document where FDocClsCd='" + cls + "'", "FTitle,FContentTxt");
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    dr["FContentTxt"] = NoHTML(dr["FContentTxt"].ToString());
                }
                return View(ds.Tables[0]);
            }
            else
            {
                DataTable dt = new DataTable();
                return View(dt);
            }
        }

        public System.Web.Mvc.FileResult ToExecl()
        {
            string issNo = Fetch.Post("hidcls");
            string dt1 = Fetch.Post("hidDateEdit1");
            string dt2 = Fetch.Post("hidDateEdit2");
            DataTable dt = new DataTable();
            string str = "";
            if (issNo != "")
            {
                if (dt1 != "" && dt2 != "")
                {
                    str = " and DATEDIFF(DAY,FPubDate,'" + dt1 + "')<=0 AND DATEDIFF(DAY,FPubDate,'" + dt2 + "')>=0 ";
                }
                else if (dt1 != "")
                {
                    str = " and DATEDIFF(DAY,FPubDate,'" + dt1 + "')<=0  ";
                }
                else if (dt2 != "")
                {
                    str = " and  DATEDIFF(DAY,FPubDate,'" + dt2 + "')>=0 ";
                }

                BLL.Common CommonBLL = new BLL.Common();
                DataSet ds = CommonBLL.GetCompareDataBySQL("t_document where FDocClsCd='" + issNo + "'" + str, "FTitle,FContentTxt");
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    dr["FContentTxt"] = NoHTML(dr["FContentTxt"].ToString());
                }
                dt = ds.Tables[0];
            }

             StringBuilder a = new StringBuilder();


            for (int i = 0; i < dt.Rows.Count; i++)
            {
                a.Append(@"



" + "第" + (i + 1) + "篇：" + dt.Rows[i]["FTitle"]);
                a.Append(@"



" + dt.Rows[i]["FContentTxt"]);
            }

            var uploadoffiepath = Server.MapPath(Url.Content("~") + string.Format("/Publish/{0}/CLSDOC/{1}{2}/", GlobalConstant.ENTITYNO, DateTime.Now.Year, DateTime.Now.Month));
            if (!Directory.Exists(uploadoffiepath))//如果不存在就创建
            {
                Directory.CreateDirectory(uploadoffiepath);
            }

            object MyFileName = uploadoffiepath + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";
            System.IO.File.WriteAllText(MyFileName.ToString(), a.ToString());

           // Microsoft.Office.Interop.Word.Application MyWord;
//            MyWord = new Microsoft.Office.Interop.Word.Application();

//            Microsoft.Office.Interop.Word.Document MyDoc;



//            Object Nothing = System.Reflection.Missing.Value;


//            MyDoc = MyWord.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

//            StringBuilder a = new StringBuilder();


//            for (int i = 0; i < dt.Rows.Count; i++)
//            {
//                a.Append(@"
//
//
//
//" + "第" + (i + 1) + "篇：" + dt.Rows[i]["FTitle"]);
//                a.Append(@"
//
//
//
//" + dt.Rows[i]["FContentTxt"]);
//            }

//            MyDoc.Paragraphs.Last.Range.Text = a.ToString();

//            MyDoc.Paragraphs.Last.Range.Font.Name = "宋体";
//            // MyDoc.Paragraphs.Last.Range.Text = this.richTextBox1.Text;
            
//            var uploadoffiepath = Server.MapPath(Url.Content("~") + string.Format("/Publish/{0}/CLSDOC/{1}{2}/", GlobalConstant.ENTITYNO, DateTime.Now.Year, DateTime.Now.Month));
//            if (!Directory.Exists(uploadoffiepath))//如果不存在就创建
//            {
//                Directory.CreateDirectory(uploadoffiepath);
//            }

//            object MyFileName = uploadoffiepath+DateTime.Now.ToString("yyyyMMddHHmmss")+".doc";
//            //将WordDoc文档对象的内容保存为DOC文档 

//            MyDoc.SaveAs(ref MyFileName, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
//            //关闭wordDoc文档对象 
//            MyDoc.Close(ref Nothing, ref Nothing, ref Nothing); //会产生多义性警告，暂时未解决  
//            //关闭wordApp组件对象 
//            MyWord.Quit(ref Nothing, ref Nothing, ref Nothing);//会产生多义性警告，暂时未解决 
//            // MessageBox.Show("文档创建成功");             //本文来自CSDN博客，转载请标明出处：

            return File(MyFileName.ToString(), "text/plain","信息.txt");
            //return View("Index", dt);
        }

        

        //public System.Web.Mvc.FileResult ToExecl()
        //{
        //    string issNo = Fetch.Post("hidcls");
        //    string dt1 = Fetch.Post("hidDateEdit1");
        //    string dt2 = Fetch.Post("hidDateEdit2");
        //    DataTable dt = new DataTable();
        //    string str = "";
        //    if (issNo != "")
        //    {
        //        if (dt1 != "" && dt2 != "")
        //        {
        //            str = " and DATEDIFF(DAY,FPubDate,'" + dt1 + "')<=0 AND DATEDIFF(DAY,FPubDate,'" + dt2 + "')>=0 ";
        //        }
        //        else if (dt1 != "")
        //        {
        //            str = " and DATEDIFF(DAY,FPubDate,'" + dt1 + "')<=0  ";
        //        }
        //        else if (dt2 != "")
        //        {
        //            str = " and  DATEDIFF(DAY,FPubDate,'" + dt2 + "')>=0 ";
        //        }

        //        BLL.Common CommonBLL = new BLL.Common();
        //        DataSet ds = CommonBLL.GetCompareDataBySQL("t_document where FDocClsCd='" + issNo + "'" + str, "FTitle,FContentTxt");
        //        foreach (DataRow dr in ds.Tables[0].Rows)
        //        {
        //            dr["FContentTxt"] = NoHTML(dr["FContentTxt"].ToString());
        //        }
        //        dt = ds.Tables[0];
        //    }


        //    int totalRowCount = 1;
        //    List<Model.XlsModel> xlsModelList = new List<Model.XlsModel>();

        //    int colCount = 4;

        //    Model.XlsModel xlsModel = new Model.XlsModel();
        //    xlsModel.RowSpan = 1;
        //    xlsModel.RowIndex = totalRowCount;
        //    xlsModel.Title = "标题";
        //    xlsModel.ColSpan = 10;
        //    xlsModel.HAlign = Model.XlsModel.HorizontalAlign.Center;

        //    xlsModelList.Add(xlsModel);

        //    xlsModel = new Model.XlsModel();
        //    xlsModel.RowSpan = 1;
        //    xlsModel.RowIndex = totalRowCount;
        //    xlsModel.Title = "内容";
        //    xlsModel.ColSpan = 10;
        //    xlsModel.HAlign = Model.XlsModel.HorizontalAlign.Center;
        //    xlsModelList.Add(xlsModel);



        //    for (int i = 0; i < dt.Rows.Count; i++)
        //    {
        //        totalRowCount++;
        //        foreach (System.Data.DataColumn dc in dt.Columns)
        //        {
        //            decimal d = 0;
        //            if (decimal.TryParse(dt.Rows[i][dc.ColumnName].ToString(), out d))
        //            {
        //                if (d != 0)
        //                {
        //                    xlsModel = new Model.XlsModel();
        //                    xlsModel.RowIndex = totalRowCount;
        //                    xlsModel.HAlign = Model.XlsModel.HorizontalAlign.Right;
        //                    xlsModel.Title = dt.Rows[i][dc.ColumnName].ToString();
        //                    xlsModelList.Add(xlsModel);
        //                }
        //                else
        //                {
        //                    xlsModel = new Model.XlsModel();
        //                    xlsModel.RowIndex = totalRowCount;
        //                    xlsModel.ColSpan = 10;
        //                    xlsModel.HAlign = Model.XlsModel.HorizontalAlign.Right;
        //                    xlsModel.Title = "";
        //                    xlsModelList.Add(xlsModel);
        //                }
        //            }
        //            else
        //            {
        //                xlsModel = new Model.XlsModel();
        //                xlsModel.RowIndex = totalRowCount;
        //                xlsModel.ColSpan = 10;
        //                xlsModel.Title = dt.Rows[i][dc.ColumnName].ToString();
        //                xlsModel.HAlign = Model.XlsModel.HorizontalAlign.Left;
        //                xlsModelList.Add(xlsModel);
        //            }
        //        }
        //    }

        //    List<Model.XlsModel_Column> xlsModelColumns = new List<Model.XlsModel_Column>();
        //    xlsModelColumns.Add(new Model.XlsModel_Column()
        //    {
        //        ColumnIndexStart = 0,
        //        ColumnIndexEnd = 30,
        //        Width = 50
        //    });

        //    List<Model.XlsModel_Row> xlsModelRows = new List<Model.XlsModel_Row>();
        //    ushort rowCount = (ushort)(totalRowCount);
        //    xlsModelRows.Add(new Model.XlsModel_Row()
        //    {
        //        RowIndexStart = 1,
        //        RowIndexEnd = 1,
        //        RowHeight = 23
        //    });

        //    xlsModelRows.Add(new Model.XlsModel_Row()
        //    {
        //        RowIndexStart = 2,
        //        RowIndexEnd = 7,
        //        RowHeight = 12

        //    });
        //    xlsModelRows.Add(new Model.XlsModel_Row()
        //    {
        //        RowIndexStart = 8,
        //        RowIndexEnd = rowCount,
        //        RowHeight = 15

        //    });

        //    Model.ExcelTitleFont excelTitleFont = new Model.ExcelTitleFont()
        //    {
        //        FontName = "宋体",
        //        FontSize = 18,
        //        Bold = true
        //    };

        //    byte[] b = Common.ExcelClass.ExportToExcelReturnByte("", "信息.xls", "信息", excelTitleFont, totalRowCount, xlsModelList, xlsModelColumns, xlsModelRows);

        //    string name = "信息.xls";
        //    return File(b, "application/vnd.ms-excel", HttpUtility.UrlEncode(name));

        //}


        /// <summary>
        /// 去除HTML标签，获取文字
        /// </summary>
        /// <param name="Htmlstring"></param>
        /// <returns></returns>
        public static string NoHTML(string Htmlstring)
        {
            //删除脚本  
            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            //删除HTML  
            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"([/r/n])[/s]+", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "/xa1", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "/xa2", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "/xa3", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "/xa9", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&#(/d+);", "", RegexOptions.IgnoreCase);
            Htmlstring.Replace("<", "");
            Htmlstring.Replace(">", "");
            Htmlstring.Replace("/r/n", "");
            Htmlstring= Htmlstring.Replace("&ldquo;", "“");
            Htmlstring = Htmlstring.Replace("&rdquo;", "”");
            Htmlstring = Htmlstring.Replace("&mdash;", "—");
            Htmlstring = Htmlstring.Replace("&hellip;", "…");
            //Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
            return Htmlstring;
        }

    }
}
